<template>
  <div class="classification-page">
    <div class="formSearch">
      <el-form :inline="true" :model="formInline">
        <!-- <el-form-item label="菜单名">
          <el-input v-model="formInline.permissionName" placeholder="请输入菜单名" />
        </el-form-item> -->
        <el-form-item>
          <!-- <el-button type="primary" plain @click="search">查询</el-button> -->
          <!-- <el-button type="info" plain @click="clear">重置</el-button> -->
          <!-- <el-button type="success" plain @click="add(1)">新增父级目录</el-button>
          <el-button type="success" plain @click="add(2)">新增子级菜单</el-button> -->
          <el-button
            type="primary"
            v-permission="['customerMage:add']"
            @click="add()"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="classifyId"
      border
      :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="classifyName" label="商品类别" />
      <el-table-column prop="classifyLevel" label="商品等级" />
      <el-table-column prop="status" label="商品状态" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="status" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.native.prevent="brandRow(scope.row)"
            v-if="scope.row.classifyLevel == 3"
            >绑定品牌</el-button
          >
          <el-button
            type="text"
            @click.native.prevent="parameterRow(scope.row)"
            v-if="scope.row.classifyLevel == 3"
            >绑定属性</el-button
          >
          <el-button
            type="text"
            v-permission="['customerMage:detail']"
            @click.native.prevent="checkRow(scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            v-permission="['customerMage:edit']"
            @click.native.prevent="updateRow(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            v-permission="['customerMage:detele']"
            @click.native.prevent="deleteRow(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="fenye">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <edit-dialog
      ref="edit"
      :dialog-visible="dialog.isVisible"
      :type="dialog.type"
      @close="editClose"
      @success="getProductCategory"
    />

    <!--绑定品牌-->
    <el-dialog
      title="绑定品牌"
      :visible.sync="brandDialog"
      width="600px"
      center
      :close-on-click-modal="false"
    >
      <div>
        <el-table
          ref="multipleTable"
          :data="options"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="30">
          </el-table-column>
          <el-table-column label="名称" align="center" width="120">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column
            prop="brandImage"
            align="center"
            label="品牌Logo"
            width="120"
          >
            <template slot-scope="scope"
              ><img
                :src="scope.row.brandImage"
                style="width: 50px; height: 50px"
            /></template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.createTime || "" }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="brandDialog = false">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>

    <!--绑定属性-->
    <parameter-dialog
      ref="parameter"
      v-if="paradialog"
      :dialog-visible="paradialog"
      :classifyId="classifyId"
      @close="parameterClose"
      @success="getProductCategory"
    />

    <!-- *************对话框开始************* -->
    <el-dialog
      :title="userState == 1 ? '新增' : userState == 2 ? '查看' : '编辑菜单'"
      :visible.sync="addFormDialog"
      width="500px"
      center
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="ruleForm"
          :model="addForm"
          label-width="100px"
          :rules="userRules"
        >
          <el-form-item label="上级类目" prop="classifyPid">
            <treeselect
              v-model="addForm.classifyPid"
              :options="menus"
              :normalizer="normalizer"
              style="width: 350px"
              placeholder="选择上级类目"
            />
          </el-form-item>
          <el-form-item label="分类名称" prop="classifyName">
            <el-input
              v-model="addForm.classifyName"
              placeholder="请输入分类名称"
            />
          </el-form-item>
          <el-form-item label="分类图片地址" prop="classifyImage">
            <el-upload
              :class="{ uoloadSty: showBtnImg, disUoloadSty: noneBtnImg }"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
              :data="dataObj"
              :file-list="addForm.classifyImage"
              :limit="1"
              :on-success="handleImageSuccess"
              :action="action"
            >
              <i slot="default" class="el-icon-plus" />
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.imgPath"
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in" />
                  </span>

                  <span
                     v-if="userState!=2"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete" />
                  </span>
                </span>
              </div>
            </el-upload>

            <!-- <el-input v-model="addForm.classifyImage" placeholder="请输入分类图片地址" /> -->
          </el-form-item>
          <el-form-item label="排序值" prop="sort">
            <el-input
              v-model="addForm.sort"
              type="number"
              placeholder="请输入排序值"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialog = false">取 消</el-button>
        <el-button type="primary" @click="addForm_enter('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 查看放大图片 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import IconSelect from "@/components/IconSelect";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  commdityClassGetAll,
  commdityClassDelete,
  brandList,
  brandclassifyId,
  getbrandclassifyId,
  commdityClassAdd,
  commdityClassUpdate,
} from "@/api/renovation";
import EditDialog from "./Edit";
import ParameterDialog from "./Parameter";
const BASEURL = process.env.VUE_APP_DOMAIN_PREFIX;
export default {
  components: {
    IconSelect,
    Treeselect,
    EditDialog,
    ParameterDialog,
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      showBtnImg: true,
      noneBtnImg: false,
      normalizer(node) {
        return {
          id: node.classifyId,
          label: node.classifyName,
          children: node.children,
        };
      },
      menus: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        path: [{ required: true, message: "请输入地址", trigger: "blur" }],
      },
      formparams: {},
      userRules: {
        classifyPid: [
          { required: true, message: "请选择上级类目", trigger: "blur" },
        ],
        classifyName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        classifyImage: [
          { required: true, message: "请上传分类图片地址", trigger: "blur" },
        ],
      },
      action: BASEURL + "/file/upload",
      dataObj: {
        folderId: 1,
      },
      headers: {
        Authorization: "",
      },
      multipleSelection: "",
      userState: 1, //1新增  2查看 3编辑
      fileList: [
        {
          imgPath:
            "http://file.shop.quanqiushou.net.cn/file/2021/09/5433c27a16e54b379912a133757e4f0c_1626316522(1).jpg",
        },
      ],
      addForm: {
        classifyImage: [],
      },
      addFormDialog: false,
      formInline: {},
      row: {},
      classifyId: "",
      paradialog: false, //添加属性
      form: {
        brandIds: "",
        classifyId: "",
      },
      selsectValue: "",
      options: [],
      brandDialog: false, //绑定品牌
      dialogVisible: false,
      formParams: {
        page: 1,
        pageSize: 10,
      },
      total: 1,
      tableData: [],
      currentPage: 1,
      dialog: {
        type: "add",
        isVisible: false,
      },

      tableData: [],
      multipleSelection: [],
    };
  },
  created() {
    this.getProductCategory();
    this.getAll(this.formParams);
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleImageSuccess(response) {
      const { url } = response.data;
      this.addForm.classifyImage.push({
        imgPath: url,
      });
      this.showBtnImg=false;
      this.noneBtnImg=true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.imgPath;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file) {
      this.showBtnImg=true;
      this.noneBtnImg=false;
      const { imgPath } = file;
      this.addForm.classifyImage = this.addForm.classifyImage.filter((item) => {
        return item.imgPath !== imgPath;
      });
    },

    addForm_enter(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (this.userState == 1) {
            if (this.addForm.classifyImage.length) {
              this.addForm.classifyImage =
                this.addForm.classifyImage[0].imgPath;
            }
            commdityClassAdd(this.addForm).then((res) => {
              if (res.data) {
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
              }
              this.getAll(this.formParams);
              this.addFormDialog = false;
            });
          } else {
            let form = {
              classifyId: this.addForm.classifyId,
              classifyImage: this.addForm.classifyImage[0].imgPath,
              classifyName: this.addForm.classifyName,
              sort: parseInt(this.addForm.sort),
            };
            commdityClassUpdate(form).then((res) => {
              if (res.data) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
              }
              this.getAll(this.formParams);
              this.addFormDialog = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    //新增商品类别
    add() {
      this.userState = 1;
      this.showBtnImg=true;
      this.noneBtnImg=false;
      this.addForm =  {
        classifyImage: []
      };
      this.addFormDialog = true
    },
    // 查询
    search() {
      this.total = 1;
      this.formInline.page = 1;
      this.getAll(this.formInline);
    },
    // 清除
    clear() {
      this.formInline = {
        permissionName: "", // 搜索字段
        page: "1", // 当前页
        pageSize: "10", // 每页记录数
      };
      this.getAll(this.formInline);
    },
    parameterRow(row) {
      this.paradialog = true;
      this.classifyId = row.classifyId;
    },
    sure() {
      this.form.classifyId = this.row.classifyId;
      let obj = {
        classifyId: this.form.classifyId,
        brandIds: [],
      };
      obj.brandIds = this.multipleSelection.map((item) => {
        return item.id;
      });
      brandclassifyId(obj).then((res) => {
        if (res.data) {
          this.$message({
            type: "success",
            message: "绑定成功!",
          });
          this.brandDialog = false;
        }
      });
    },

    brandRow(row) {
      this.row = row;
      getbrandclassifyId(row.classifyId).then((res) => {
        let tableData = [];
        res.data.forEach((item, index) => {
          this.options.forEach((items, indexss) => {
            if (item == items.id) {
              tableData.push(items);
            }
          });
        });
        this.toggleSelection(tableData);
      });
      brandList().then((res) => {
        this.options = res.data;
      });
      this.form.classifyId = row.classifyId;
      this.brandDialog = true;
    },

    handleSizeChange(val) {
      this.formParams.pageSize = val;
      this.getAll(this.formParams);
    },
    handleCurrentChange(val) {
      this.formParams.page = val;
      this.getAll(this.formParams);
    },
    fetch(config) {
      const { limit, page } = config;
      this.formParams.pageIndex = page || 1;
      this.formParams.pageSize = limit || 10;
      this.getProductCategory();
    },
    editClose() {
      this.dialog.isVisible = false;
    },
    parameterClose() {
      this.paradialog = false;
    },
    // 编辑
    updateRow(row) {
      this.userState = 3;
      this.showBtnImg=false;
      this.noneBtnImg=true;
      this.addFormDialog = true;
      this.addForm = row;
      //组合classifyImage数据结构
      let array = new Array();
      array.push({
        imgPath: row.classifyImage,
      });
      this.addForm.classifyImage = array;
      this.getAll(this.formParams);
    },
    // 查看
    checkRow(row) {
      this.userState = 2;
      this.showBtnImg=false;
      this.noneBtnImg=true;
      this.addFormDialog = true;
      this.addForm = row;
      let array1 = new Array();
      array1.push({
        imgPath: row.classifyImage,
      });
      this.addForm.classifyImage = array1;
      this.getAll(this.formParams);
    },
    // 删除
    async deleteRow(row) {
      this.$confirm("此操作将永久删除该类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          commdityClassDelete({ classifyId: row.classifyId }).then((res) => {
            if (res.code === "") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
            this.getAll(this.formParams);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    getProductCategory() {
      this.paradialog = false;
      this.getAll(this.formParams);
    },
    async getAll(formParams) {
      const res = await commdityClassGetAll(formParams);
      const data = res.data.content;
      data.forEach((item) => {
        if (item.children.length) {
          item.children.forEach((items) => {
            if (items.children.length) {
              items.children.forEach((itemss) => {
                itemss.isDisabled = true;
                if (!itemss.children.length) delete itemss.children;
              });
            } else {
              delete items.children;
            }
          });
        } else {
          delete item.children;
        }
      });
      this.menus = [];
      let menu = { classifyId: 0, classifyName: "顶级类目", children: [] };
      menu.children = res.data.content;
      this.menus.push(menu);
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
    },
  },
};
</script>
<style lang="scss" scoped>
@import url("../../../styles/elDialog.scss");

::v-deep .el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 148px;
}
::v-deep .disUoloadSty .el-upload--picture-card {
  display: none !important; /* 上传按钮隐藏 */
}

.classification-page {
  padding: 15px 20px;
  .toolbar {
    margin-bottom: 15px;
    text-align: right;
  }
}
</style>
